package com.example.yichuangyun.ui.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ItemCompanyAndProductInfoBinding;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.CompanyAndProductModel;
import com.example.yichuangyun.model.business.CompanyDataModel;
import com.example.yichuangyun.model.business.ProductModel;
import com.example.yichuangyun.ui.activity.business.AddBusinessActivity;
import com.example.yichuangyun.utils.CashierInputFilter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

@SuppressLint("NotifyDataSetChanged")
public class CompanyAndProductAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private List<CompanyAndProductModel> mData;
    /**
     * 关联企业
     */
    private final List<String> companyData = new ArrayList<>();
    private final OnChangeButtonStatusListener onChangeButtonStatusListener;
    private OnChooseProductListener onChooseProductListener;
    private final String contactId;

    public CompanyAndProductAdapter(Context context, List<CompanyAndProductModel> mData, OnChangeButtonStatusListener onChangeButtonStatusListener, String contactId) {
        this.context = context;
        this.mData = mData;
        this.contactId = contactId;
        this.onChangeButtonStatusListener = onChangeButtonStatusListener;
        companyData.add(context.getString(R.string.company_established));
        companyData.add(context.getString(R.string.company_to_be_established));
        companyData.add(context.getString(R.string.personal_business));
    }

    public void onRefresh(List<CompanyAndProductModel> mList) {
        if (mList != null) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.clear();
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    public void addData(List<CompanyAndProductModel> mList) {
        if (mList != null && mList.size() != 0) {
            if (mData == null) {
                mData = new ArrayList<>();
            }
            this.mData.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemCompanyAndProductInfoBinding itemContactPersonInfoBinding = ItemCompanyAndProductInfoBinding.inflate(LayoutInflater.from(context), parent, false);
        return new MyViewHolder(itemContactPersonInfoBinding);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        if (holder instanceof MyViewHolder) {
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            CompanyAndProductModel model = mData.get(position);
            myViewHolder.binding.ivAddInfo.setBackgroundResource(position == 0 ? R.drawable.shape_add_number : R.drawable.shape_del_bg_bbc2cb);
            myViewHolder.binding.ivAddInfo.setImageResource(position == 0 ? R.mipmap.icon_add_write : R.mipmap.icon_reduce_write);

            // 0企业业务(已设立)、 1企业业务(拟设立) 2、个人业务
            if (model.getServiceCategory() == 0) {
                myViewHolder.binding.textCompanyNameText.setVisibility(View.VISIBLE);
                myViewHolder.binding.textCompanyNameText.setText(context.getString(R.string.company_name_star));
                myViewHolder.binding.tvRelationCompany.setText(context.getString(R.string.company_established));
            } else if (model.getServiceCategory() == 1) {
                myViewHolder.binding.textCompanyNameText.setVisibility(View.VISIBLE);
                myViewHolder.binding.textCompanyNameText.setText(context.getString(R.string.company_name));
                myViewHolder.binding.tvRelationCompany.setText(context.getString(R.string.company_to_be_established));
            } else {
                myViewHolder.binding.llCompanyName.setVisibility(View.GONE);
                myViewHolder.binding.tvRelationCompany.setText(context.getString(R.string.personal_business));
            }

            myViewHolder.binding.etMoney.setFilters(new InputFilter[]{new CashierInputFilter()});
            if (model.getProducts() != null && model.getProducts().size() > 0) {
                StringBuilder builder = new StringBuilder();
                for (ProductModel productModel : model.getProducts()) {
                    builder.append(productModel.getProductName()).append("，");
                }
                myViewHolder.binding.tvProductName.setText(builder.substring(0, builder.toString().length() - 1));
            } else {
                myViewHolder.binding.tvProductName.setText("");
            }

            myViewHolder.binding.ivAddInfo.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                if (position == 0) {
                    mData.add(TextUtils.isEmpty(contactId) ? new CompanyAndProductModel() : new CompanyAndProductModel(contactId));
                } else {
                    mData.remove(model);
                }
                notifyDataSetChanged();
                onChangeButtonStatusListener.onChangeListener();
            });

            myViewHolder.binding.rlRelationCompany.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                SinglePickerView singlePickerView = new SinglePickerView((Activity) context, context.getString(R.string.work_type), companyData) {
                    @Override
                    public void confirm(String label, int position1) {
                        // 0企业业务(已设立)、 1企业业务(拟设立) 2、个人业务
                        int category = label.equals(context.getString(R.string.company_established)) ? 0 : label.equals(context.getString(R.string.company_to_be_established)) ? 1 : 2;
                        if (category != model.getServiceCategory()) {
                            myViewHolder.binding.etCompanyName.setText("");
                            model.setServiceCategory(category);
                            model.setProducts(null);
                            notifyItemChanged(position);
                            onChangeButtonStatusListener.onChangeListener();
                        }
                    }
                };
                singlePickerView.showSinglePickerView();
            });

            myViewHolder.binding.rlAddProduct.setOnClickListener(v -> {
                int category = myViewHolder.binding.tvRelationCompany.getText().toString().equals(context.getString(R.string.personal_business)) ? 2 : 1;
                onChooseProductListener.onProductListener(model, category);
                onChangeButtonStatusListener.onChangeListener();
            });

            myViewHolder.binding.etCompanyName.setOnEditorActionListener((v, actionId, event) -> {
                if (CommonUtil.isCanClick()) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        String companyName = myViewHolder.binding.etCompanyName.getText().toString();
                        if (!TextUtils.isEmpty(companyName)) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("keyword", companyName);
                            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getCompanyByQxb(requestBody), new MyObserver<HttpRespond<CompanyDataModel>>() {
                                @Override
                                protected void onSuccess(HttpRespond<CompanyDataModel> companyDataModelHttpRespond) {
                                    if (Constant.SUCCESS == companyDataModelHttpRespond.code) {
                                        if (null != companyDataModelHttpRespond.data) {
                                            List<CompanyDataModel.CompanyInfoModel> list = companyDataModelHttpRespond.data.getItems();
                                            if (null != list && list.size() > 0) {
                                                List<String> mComList = new ArrayList<>();
                                                for (CompanyDataModel.CompanyInfoModel comModel : list) {
                                                    mComList.add(comModel.getName() /* + "(" + comModel.getCreditNo() + ")" */);
                                                }
                                                CommonUtil.closeKeyboard((AddBusinessActivity) context);
                                                SinglePickerView singlePickerView = new SinglePickerView((AddBusinessActivity) context, context.getString(R.string.choose_company), mComList) {
                                                    @Override
                                                    public void confirm(String label, int position) {
                                                        model.setCompName(list.get(position).getName());
                                                        model.setCreditNo(list.get(position).getCreditNo());
                                                        onChangeButtonStatusListener.onChangeListener();
                                                        notifyDataSetChanged();
                                                    }
                                                };
                                                singlePickerView.showSinglePickerView();
                                            } else {
                                                model.setCreditNo("");
                                            }
                                        }
                                    } else {
                                        ToastHelper.show(companyDataModelHttpRespond.msg);
                                    }
                                }
                            });
                        } else {
                            model.setCreditNo("");
                        }
                        return true;
                    }
                }
                return false;
            });

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (myViewHolder.binding.etCompanyName.getTag() instanceof TextWatcher) {
                myViewHolder.binding.etCompanyName.removeTextChangedListener((TextWatcher) (myViewHolder.binding.etCompanyName.getTag()));
            }

            // 第2步：移除TextWatcher之后，设置EditText的Text。
            myViewHolder.binding.etCompanyName.setText(model.getCompName());

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (TextUtils.isEmpty(editable.toString())) {
                        model.setCompName("");
                        model.setCreditNo("");
                    } else {
                        model.setCreditNo(!editable.toString().equals(model.getCompName()) ? "" : model.getCreditNo());
                        model.setCompName(editable.toString());
                    }
                    onChangeButtonStatusListener.onChangeListener();
                }
            };
            myViewHolder.binding.etCompanyName.addTextChangedListener(watcher);
            myViewHolder.binding.etCompanyName.setTag(watcher);

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (myViewHolder.binding.etMoney.getTag() instanceof TextWatcher) {
                myViewHolder.binding.etMoney.removeTextChangedListener((TextWatcher) (myViewHolder.binding.etMoney.getTag()));
            }

            // 第2步：移除TextWatcher之后，设置EditText的Text。
            myViewHolder.binding.etMoney.setText(model.getExpectFree());

            TextWatcher watcher2 = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    model.setExpectFree(TextUtils.isEmpty(editable.toString().trim()) ? "" : editable.toString());
                    onChangeButtonStatusListener.onChangeListener();
                }
            };
            myViewHolder.binding.etMoney.addTextChangedListener(watcher2);
            myViewHolder.binding.etMoney.setTag(watcher2);

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (myViewHolder.binding.etNote.getTag() instanceof TextWatcher) {
                myViewHolder.binding.etNote.removeTextChangedListener((TextWatcher) (myViewHolder.binding.etNote.getTag()));
            }

            // 第2步：移除TextWatcher之后，设置EditText的Text。
            myViewHolder.binding.etNote.setText(model.getRemark());

            TextWatcher watcher3 = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    model.setRemark(TextUtils.isEmpty(editable.toString().trim()) ? "" : editable.toString());
                    onChangeButtonStatusListener.onChangeListener();
                }
            };
            myViewHolder.binding.etNote.addTextChangedListener(watcher3);
            myViewHolder.binding.etNote.setTag(watcher3);

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (myViewHolder.binding.etWeight.getTag() instanceof TextWatcher) {
                myViewHolder.binding.etWeight.removeTextChangedListener((TextWatcher) (myViewHolder.binding.etWeight.getTag()));
            }

            // 第2步：移除TextWatcher之后，设置EditText的Text。
            myViewHolder.binding.etWeight.setText(TextUtils.isEmpty(model.getChanceWeight()) ? "1" : model.getChanceWeight());

            TextWatcher watcher4 = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (editable.toString().startsWith("0")) {
                        editable.clear();
                    }
                    model.setChanceWeight(editable.toString());
                    onChangeButtonStatusListener.onChangeListener();
                }
            };
            myViewHolder.binding.etWeight.addTextChangedListener(watcher4);
            myViewHolder.binding.etWeight.setTag(watcher4);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        ItemCompanyAndProductInfoBinding binding;

        public MyViewHolder(ItemCompanyAndProductInfoBinding itemCompanyAndProductInfoBinding) {
            super(itemCompanyAndProductInfoBinding.getRoot());
            binding = itemCompanyAndProductInfoBinding;
        }
    }

    public interface OnChangeButtonStatusListener {
        void onChangeListener();
    }

    public void setOnChooseProductListener(OnChooseProductListener onChooseProductListener) {
        this.onChooseProductListener = onChooseProductListener;
    }

    public interface OnChooseProductListener {
        void onProductListener(CompanyAndProductModel model, int category);
    }
}
